Collage

n. A piece of art made by sticking various different materials, aka PHENOMENA Magazine
Department
programming

programming

John Doe · Jan. 12, 2023, 9:59 p.m.
django migration
현재 시스템에 연결된 디스크 목록을 확인 contact@me:~$ sudo fdisk -l 추가로 연결한 하드가 있다면 아래처럼 뜸 (파티션을 나누지 않은 상태) Disk /dev/sdd: 9.1 TiB, 10000831348736 bytes, 19532873728 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 4096 bytes I/O size (minimum/optimal): 4096 bytes / 4096 bytes 외장하드를 연결했다면 아래처럼 뜸  The backup GPT table is corrupt, but the primary appears OK, so that will be used. Disk /dev/sdd: 3.7 TiB, 4000787029504 bytes, 7814037167 sectors Units: sectors of 1 * 512 = 512 bytes Sector size (logical/physical): 512 bytes / 4096 bytes I/O size (minimum/optimal): 4096 bytes / 4096 bytes Disklabel type: gpt Disk identifier: 9DB1508D-F261-47ED-BEB0-5AF9974A311C Device Start End Sectors Size Type /dev/sdd1 34 262177 262144 128M Microsoft reserved /dev/sdd2 264192 7814035455 7813771264 3.7T Microsoft basic data Partition 1 does not start on physical sector boundary. 4TB와 같이 용량이 크면 GPT 방식으로 파티션을 나누게 되는데 그러한 경우 아래 명령어 입력 contact@me:~$ sudo parted -l 파티션 나누는 자세한 방법은 생략 마운트 전에 해당영역을 포맷 contact@me:~$ sudo mkfs.ext4 /dev/sda1 mke2fs 1.44.1 (24-Mar-2018) /dev/sda1 contains a ntfs file system Proceed anyway? (y,N) y Creating filesystem with 1220804352 4k blocks and 152600576 inodes Filesystem UUID: 9DB1508D-F261-47ED-BEB0-5AF9974A311C Superblock backups stored on blocks: 32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208, 4096000, 7962624, 11239424, 20480000, 23887872, 71663616, 78675968, 102400000, 214990848, 512000000, 550731776, 644972544 Allocating group tables: done Writing inode tables: done Creating journal (262144 blocks): done Writing superblocks and filesystem accounting information: done contact@me:~$ 포맷하면 UUID가 바뀜 * ntfs 포맷 contact@me:~$ sudo mkntfs -f /dev/sdc1 다음 명령으로 연결된 하드디스크의 UUID 검색 contact@me:~$ ls -l /dev/disk/by-uuid 합계 0 lrwxrwxrwx 1 root root 10 11월 4 15:38 9DB1508D-F261-47ED-BEB0-5AF9974A311C -> ../../sda1 lrwxrwxrwx 1 root root 10 11월 4 15:38 9DB1508D-F261-47ED-BEB0-5AF9974A311C -> ../../sda2 마운트 시도했지만 아래와같이 나온다면 contact@me:~$ sudo mount -t ntfs-3g /dev/sdd2 /mpoint/x1 Mount is denied because the NTFS volume is already exclusively opened. The volume may be already mounted, or another software may use it which could be identified for example by the help of the 'fuser' command. 연결후 이미 자동으로 마운트되어있던 상태였기에 기존 마운트 해제 contact@me:~$ sudo eject /dev/sdd2 다시 시도하면 정상적으로 된다. contact@me:~$ sudo mount -t ntfs-3g /dev/sdd2 /mpoint/x1 /dev/sdd2 : 아까 sudo fdisk -l 명령어 쳤을 때 나온, Device Boot /mpoint/x1 : 하나 생성한 디렉터리 경로 * fdisk로 확인했을때 아래처럼 나왔다면 /dev/sda4  1161216 976771071 975609856 465.2G Linux filesystem ext4 포맷방식은 아래 명령으로 마운트 contact@me:~$ sudo mount -t ext4 /dev/sda4 /경로/hdd 또는 fstab에 설정 후 재부팅없이 마운트 fstab 백업 후 수정 contact@me:~$ sudo cp /etc/fstab /etc/fstab.bak contact@me:~$ sudo vi /etc/fstab UUID번호 / 마운트 위치 / 파일 시스템 종류 / 옵션 / 덤프 / 패스 - file system : 위에서 확인한 UUID - mount point : 자동으로 하드디스크를 마운트할 위치 - type : 파일 시스템의 종류. 보통은 ext4 / fat 포맷이면 vfat / ntfs 포맷이면 ntfs - options : 특이 사항이 없다면 defaults - dump : 특이 사항이 없다면 0 - pass : 특이 사항이 없다면 0  contact@me:~$ sudo nano /etc/fstab UUID=9DB1508D-F261-47ED-BEB0-5AF9974A311C / ext4 errors=remount-ro 0 1 # /boot/efi was on /dev/sda1 during installation UUID=01X5-3AB1 /boot/efi vfat umask=0077 0 1 /swapfile none swap sw 0 0 UUID=9DB1508D-F261-47ED-BEB0-5AF9974A311C /folder/A ext4 defaults 0 0 UUID=9DB1508D-F261-47ED-BEB0-5AF9974A311C /folder/B ntfs defaults 0 0 contact@me:~$ sudo mount -a *ntfs 포맷이라면 다음 명령으로 설치 contact@me:~$ sudo apt-get install ntfs-3g 디스크 파일 시스템 명령 df -h를 사용하여 마운트에 성공했는지 확인 권한설정이 필요하면 다음명령 사용 contact@me:~$ sudo chmod 777 /folder/A 우분투(Ubuntu) 하드디스크 자동으로 마운트 하는 방법 :: BlankSpace (tistory.com) * unmount 와 eject 의 차이점 nautilus - What is the difference between "Unmount", "Eject", "Safely Remove Drive" and the eject icon? - Ask Ubuntu * 추가 하드디스크 마운트 방법 [Ubuntu] 추가 하드디스크 마운트 방법 (tistory.com) * 기타 자료 Mr. P Blog: [ Ubuntu ] 우분투 외장하드 마운트 (perdupper.blogspot.com) https://bluexmas.tistory.com/727 https://m.blog.naver.com/PostView.nhn?blogId=hymne&logNo=220977353373&proxyReferer=https:%2F%2Fwww.google.com%2F https://topis.me/109 https://blog.dalso.org/uncategorized/813 [Linux] 리눅스 파티션 및 마운트 [참고 및 출처 사이트] 더보기 이론, 그림 - https://itguava.tistory.com/100 실습, 그림 - https://m.blog.naver.com/haejoon90/220749495797 1. 리눅스 파티션 기본 정보 [파티셔닝] 하나의 물리 저장장치를 시스템 내부에서 여러 디스크 공간으로 나누는 작업 Primary Partition(주 영역 파티션) 물리적 파티션 최대 4개까지의 공간으로 나눌 수 있다.(Extended Partit https://kindongsy.tistory.com/35
John Doe · Jan. 12, 2023, 8:19 a.m.
Ubuntu mount
1. 삼바설치 sudo apt-get -y update sudo apt-get -y install samba 2. 기존에 사용하고 있는 리눅스 계정을 Samba에 추가하기 위해 아래 명령어를 입력 sudo smbpasswd -a <계정명> 계정은 리눅스에 존재하는 계정이면 Samba에 계속 추가할 수 있음 3. 원본을 보존하기 위해 Samba 설정 파일을 백업 sudo cp /etc/samba/smb.conf /etc/samba/smb.conf_temp 4. Samba 설정 파일을 수정 sudo nano /etc/samba/smb.conf 5. 공유할 디렉토리를 설정하기 위해서 설정 파일의 가장 하단에 아래와 같은 형태로 입력 [multimedia] comment = multimedia directory path = /data/Multimedia valid users = id1,id2 writeable = yes read only = no create mode = 0777 directory mode = 0777 6. 파일 수정이 완료되면 저장하고 Samba 데몬을 재시작 sudo service smbd restart 위의 명령어로 삼바 데몬을 재 구동을 시켜주면 좀전에 설정한 내역들이 적용됨. * 파이썬으로 삼바접속 1. pysmb 라이브러리 설치 (https://pypi.org/project/pysmb/) 2. 예제코드 from smb.SMBConnection import SMBConnection server_ip = "10.110.10.10" # Take your server IP - I have put a fake IP :) server_name = 'myserver' # The servername for the IP above share_name = "GRUPOS" # This is the principal folder of your network that you want's to connect network_username = 'myuser' # This is your network username network_password = '***' # This is your network password machine_name = 'myuser@mac-mc70006405' # Your machine name conn = SMBConnection(network_username, network_password, machine_name, server_name, use_ntlm_v2 = True) assert conn.connect(server_ip, 139) files = conn.listPath(share_name, "/TECNOLOGIA_INFORMACAO/Dashboard Diretoria/") for item in files: print(item.filename) https://psychoria.tistory.com/678 리눅스 환경(Ubuntu)에서 개발을 편리하게! Samba 구축하기 - 코드도사 (codedosa.com) How to get a file from a network windows directory and move to my Python Django project directory? - Stack Overflow
John Doe · Jan. 12, 2023, 7:27 a.m.
Ubuntu samba
Q : pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"   A : pip install gensim config --global http.sslVerify false Just install any package with the "config --global http.sslVerify false" statement You can ignore SSL errors by setting pypi.org and files.pythonhosted.org as well as the older pypi.python.org as trusted hosts. $ pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org <package_name> Note: Sometime during April 2018, the Python Package Index was migrated from pypi.python.org to pypi.org. This means "trusted-host" commands using the old domain no longer work, but you can add both. Permanent Fix Since the release of pip 10.0, you should be able to fix this permanently just by upgrading pip itself: $ pip install --trusted-host pypi.org --trusted-host pypi.python.org --trusted-host files.pythonhosted.org pip setuptools Or by just reinstalling it to get the latest version: $ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py (… and then running get-pip.py with the relevant Python interpreter). pip install <otherpackage> should just work after this. If not, then you will need to do more, as explained below. You may want to add the trusted hosts and proxy to your config file. pip.ini (Windows) or pip.conf (unix) [global] trusted-host = pypi.python.org pypi.org files.pythonhosted.org Alternate Solutions (Less secure) Most of the answers could pose a security issue. Two of the workarounds that help in installing most of the python packages with ease would be: Using easy_install: if you are really lazy and don't want to waste much time, use easy_install <package_name>. Note that some packages won't be found or will give small errors. Using Wheel: download the Wheel of the python package and use the pip command pip install wheel_package_name.whl to install the package. https://stackoverflow.com/questions/25981703/pip-install-fails-with-connection-error-ssl-certificate-verify-failed-certi/26062583
John Doe · Jan. 12, 2023, 3:28 a.m.
ssl pip
Removing everything but numbers from String String value = string.replaceAll("[^0-9]",""); String clean1 = string1.replaceAll("[^0-9]", ""); or String clean2 = string2.replaceAll("[^\\d]", ""); Where \d is a shortcut to [0-9] character class, or String clean3 = string1.replaceAll("\\D", ""); Where \D is a negation of the \d class (which means [^0-9])   Using Match, Pattern class in java.util.regex boolean bln = Pattern.matches("^[a-zA-Z0-9]*$", this.input); ^ : 문자열의 시작 $ : 문자열의 종료 . : 임의의 한 문자(문자의 종류는 가리지 않음) | : or ? : 앞 문자가 없거나 하나있음. + : 앞 문자가 하나 이상임. * : 앞 문자가 없을 수도 무한정 많을 수도 있음을 나타냄. 만약, .* 으로 정규식이 시작한다면 시작하는 문자열과 같은 문자열이 뒤에 없거나 많을 수도 있는 경우에만 일치를 시킨다. 즉, abc 일 경우 시작문자인 a를 기준으로 a가 없을경우와 a가 무한정 많은 경우에도 true를 반환하기 때문에 abc의 경우는 true를 반환한다. [] : 문자 클래스를 지정할 때 사용. 문자의 집합이나 범위를 나타내면 두 문자 사이는 '-' 기호로 범위를 나타낸다. []내에서 ^ 가 선행하여 나타나면 not를 나타낸다. {} : 선행문자가 나타나는 횟수 또는 범위 a{3} 인 경우 a가 3번 반복된 경우 / a{3,}이면 a가 3번 이상 반복인 경우. 또한 a{3,5}인 경우 a가 3번 이상 5번 이하 반복된 경우를 나타냄 \w : 알파벳이나 숫자 \W : 알파벳이나 숫자를 제외한 문자 \d : 숫자 [0-9]와 동일 \D : 숫자를 제외한 모든 문자 ^[0-9]*$ : only number ^[a-zA-Z]*$ : only English ^[가-힣]*$ : only Korean ^[a-zA-Z0-9]*$ : English/number   e.g. 1) email : ^[a-zA-Z0-9]+@[a-zA-Z0-9]+$  or  ^[_0-9a-zA-Z-]+@[0-9a-zA-Z-]+(.[_0-9a-zA-Z-]+)*$ cellphone :  ^01(?:0|1|[6-9]) - (?:\d{3}|\d{4}) - \d{4}$ phone : ^\d{2,3} - \d{3,4} - \d{4}$ id : \d{6} \- [1-4]\d{6} IP addr : ([0-9]{1,3}) \. ([0-9]{1,3}) \. ([0-9]{1,3}) \. ([0-9]{1,3}) https://stackoverflow.com/questions/6883579/java-regular-expression-removing-everything-but-numbers-from-string   2) How to test if a String contains both letters and numbers .matches("^(?=.*[A-Z])(?=.*[0-9])[A-Z0-9]+$") The regex asserts that there is an uppercase alphabetical character (?=.*[A-Z]) somewhere in the string, and asserts that there is a digit (?=.*[0-9]) somewhere in the string, and then it checks whether everything is either alphabetical character or digit.   3) How can I de-duplicate repeated characters in a Java string? how________are_______you to how_are_you string.replaceAll("_+", "_")
John Doe · Jan. 12, 2023, 2:56 a.m.
regex
Q : Where can I download JSTL taglibs? i.e. jstl.jar and standard.jar A : If you're running a Servlet 2.5 compatible container and the web.xml is declared as at least Servlet 2.5, then you should be able to use the new JSTL 1.2 instead. Note that JSTL 1.2 does not require a standard.jar. Q : The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path A : Add a runtime first and select project properties. Then check the server name from the 'Runtimes' tab Q : Remove html tags from string using java A :  String noHTMLString = htmlString.replaceAll("\\<.*?>",""); Using Jsoup public static String html2text(String html) { return Jsoup.parse(html).text(); } https://stackoverflow.com/questions/4432560/remove-html-tags-from-string-using-java Q : JSPX A : https://jspx-bay.sourceforge.net/ Q : Apache Jakarta A : http://archive.apache.org/dist/jakarta/ Q : Prevent download attempts of videos in a video server A : Silverlight might be an idea to start with. Q : mp3 header information reader not working A : import org.farng.mp3.MP3File; you need to call mp3file.seekMP3Frame(); before attempting to retrieve bitrate, this method will read the file headers including the bitrate. or use http://www.jthink.net/jaudiotagger/examples_id3.jsp Q : How to get the message in a custom error page (Tomcat)? A : <c:out value="${requestScope['javax.servlet.error.message']}"/> javax.servlet.error.status_code java.lang.Integer javax.servlet.error.exception_type java.lang.Class javax.servlet.error.message java.lang.String javax.servlet.error.exception java.lang.Throwable javax.servlet.error.request_uri java.lang.String javax.servlet.error.servlet_name java.lang.String * <c:catch> Tag <%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %> <html> <head> <title><c:catch> Tag Example</title> </head> <body> <c:catch var ="catchException"> <% int x = 5/0;%> </c:catch> <c:if test = "${catchException != null}"> <p>The exception is : ${catchException} <br /> There is an exception: ${catchException.message}</p> </c:if> </body> </html> Q : Get current action in jsp - struts2 A :  <s:url forceAddSchemeHostAndPort="true" includeParams="all"/> Q : Oracle date to Java date A : little h for "Hour in am/pm (1-12)" and H for "Hour in day (0-23)" see here: SimpleDateFormat SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S"); Date date = dateFormat.parse("2011-08-19 06:11:03.0"); Q : How to get previous URL? A :  HttpServletRequest.getHeader("Referer"); Q : [JSP] 파일 다운로드창에서 한글깨짐 방지? A : response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "utf-8") + ";");
John Doe · Jan. 12, 2023, 2:03 a.m.
This is a proof of concept only Disclaimer: Before I get a bunch of hate mail about the, obviously, horrible things I've done to make this work, I stole most of the painting code straight out of the source, this is how it's actually done within the look and feel code itself :P I've also gone to the nth degree, meaning that I've literally assumed that you wanted the row headers to look like the column headers. If this isn't a requirement, it would be SO much easier to do... Okay, this is a basic proof of concept, which provides the means to generate the row header and render them the same way as they are normally, just as row headers instead. Things that need to be added/supported: Detect when the table model is changed (that is, a new table model is set to the table) Detect when the column model is changed (that is, a new column model is set to the table) Much of this functionality would probably need to be added to the TableWithRowHeader implementation... Basically, what this "tries" to do, is create a custom row header, based on a JTableHeader, remove the existing column header and add itself into the row header view position of the enclosing JScrollPane. import java.awt.BorderLayout; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JViewport; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.event.ChangeEvent; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableColumnModelEvent; import javax.swing.event.TableColumnModelListener; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; public class TableRowHeaderTest { public static void main(String[] args) { new TableRowHeaderTest(); } public TableRowHeaderTest() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } Object rowData1[][] = { {"", "", "", ""}, {"", "", "", ""}, {"", "", "", ""}, {"", "", "", ""} }; Object columnNames1[] = {"HEADER 1", "HEADER 2", "HEADER 3", "HEADER 4"}; JTable table1 = new TableWithRowHeader(rowData1, columnNames1); table1.getColumnModel().getColumn(0).setPreferredWidth(120); JScrollPane scrollPane1 = new JScrollPane(table1); scrollPane1.setColumnHeaderView(null); JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(scrollPane1); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } public class TableWithRowHeader extends JTable { private TableRowHeader rowHeader; public TableWithRowHeader(final Object[][] rowData, final Object[] columnNames) { super(rowData, columnNames); rowHeader = new TableRowHeader(this); } @Override protected void configureEnclosingScrollPane() { // This is required as it calls a private method... super.configureEnclosingScrollPane(); Container parent = SwingUtilities.getUnwrappedParent(this); if (parent instanceof JViewport) { JViewport port = (JViewport) parent; Container gp = port.getParent(); if (gp instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane) gp; JViewport viewport = scrollPane.getViewport(); if (viewport == null || SwingUtilities.getUnwrappedView(viewport) != this) { return; } scrollPane.setColumnHeaderView(null); scrollPane.setRowHeaderView(rowHeader); } } } } public class TableRowHeader extends JTableHeader { private JTable table; public TableRowHeader(JTable table) { super(table.getColumnModel()); this.table = table; table.getColumnModel().addColumnModelListener(new TableColumnModelListener() { @Override public void columnAdded(TableColumnModelEvent e) { repaint(); } @Override public void columnRemoved(TableColumnModelEvent e) { repaint(); } @Override public void columnMoved(TableColumnModelEvent e) { repaint(); } @Override public void columnMarginChanged(ChangeEvent e) { repaint(); } @Override public void columnSelectionChanged(ListSelectionEvent e) { // Don't care about this, want to highlight the row... } }); table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { repaint(); } }); } public JTable getTable() { return table; } @Override public Dimension getPreferredSize() { Dimension size = new Dimension(); JTable table = getTable(); if (table != null) { TableColumnModel model = table.getColumnModel(); if (model != null) { for (int index = 0; index < model.getColumnCount(); index++) { TableColumn column = model.getColumn(index); TableCellRenderer renderer = column.getHeaderRenderer(); if (renderer == null) { renderer = getDefaultRenderer(); } Component comp = renderer.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, -1, index); size.width = Math.max(comp.getPreferredSize().width, size.width); size.height += table.getRowHeight(index); } } } return size; } /** * Overridden to avoid propagating a invalidate up the tree when the * cell renderer child is configured. */ @Override public void invalidate() { } /** * If the specified component is already a child of this then we don't bother doing anything - stacking order doesn't matter for cell renderer components * (CellRendererPane doesn't paint anyway). */ @Override protected void addImpl(Component x, Object constraints, int index) { if (x.getParent() == this) { return; } else { super.addImpl(x, constraints, index); } } @Override protected void paintComponent(Graphics g) { // super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.setColor(getBackground()); g2d.fillRect(0, 0, getWidth(), getHeight()); JTable table = getTable(); if (table != null) { int width = getWidth(); TableColumnModel model = table.getColumnModel(); if (model != null) { for (int index = 0; index < model.getColumnCount(); index++) { TableColumn column = model.getColumn(index); TableCellRenderer renderer = column.getHeaderRenderer(); if (renderer == null) { renderer = getDefaultRenderer(); } boolean selected = table.getSelectedRow() == index; Component comp = renderer.getTableCellRendererComponent(table, column.getHeaderValue(), selected, false, 0, index); add(comp); comp.validate(); int height = table.getRowHeight(index) - 1; comp.setBounds(0, 0, width, height); comp.paint(g2d); comp.setBounds(-width, -height, 0, 0); g2d.setColor(table.getGridColor()); g2d.drawLine(0, height, width, height); g2d.translate(0, height + 1); } } } g2d.dispose(); removeAll(); } } } Disclaimer: This is likely to blow up in your face. I make no checks for preventing the header from responding to things like changes to the column row sortering and ... in theory ... it shouldn't try and "resize" the column but I didn't test that... https://stackoverflow.com/questions/26248084/how-to-display-row-header-on-jtable-instead-of-column-header
John Doe · Jan. 12, 2023, 1:36 a.m.
JTable swing
  • 1
  • 2
  • 3
  • 4
  • 5 (current)