Collage

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

programming

Parse Alexa API XML Response
1. Send a request to the following Alexa API. https://data.alexa.com/data?cli=10&url=phenomena.com 2. The Alexa API will return the following XML response. The Alexa ranking is inside the POPULARITY element, the TEXT attribute. <!-- Need more Alexa data? Find our APIs here: https://aws.amazon.com/marketplace/seller-profile?id=4a9dbf38-88b1-4e87-a459-271154a77d2e --> <ALEXA VER="0.9" URL="phenomena.com/" HOME="0" AID="=" IDN="phenomena.com/"> <SD> <POPULARITY URL="phenomena.com/" TEXT="3713994" SOURCE="panel"/> <REACH RANK="3404850"/> <RANK DELTA="+652325"/> </SD> </ALEXA> 3. We use a DOM parser to directly select the POPULARITY element and print out the value of the TEXT attribute. package com.bad.blood.test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class ReadXmlAlexaApi { private static final String ALEXA_API = "http://data.alexa.com/data?cli=10&url="; private final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); public static void main(String[] args) { ReadXmlAlexaApi obj = new ReadXmlAlexaApi(); int alexaRanking = obj.getAlexaRanking("phenomena.com"); System.out.println("Ranking: " + alexaRanking); } public int getAlexaRanking(String domain) { int result = 0; String url = ALEXA_API + domain; try { URLConnection conn = new URL(url).openConnection(); try (InputStream is = conn.getInputStream()) { // unknown XML better turn on this dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); DocumentBuilder dBuilder = dbf.newDocumentBuilder(); Document doc = dBuilder.parse(is); Element element = doc.getDocumentElement(); // find this tag "POPULARITY" NodeList nodeList = element.getElementsByTagName("POPULARITY"); if (nodeList.getLength() > 0) { Element elementAttribute = (Element) nodeList.item(0); String ranking = elementAttribute.getAttribute("TEXT"); if (!"".equals(ranking)) { result = Integer.parseInt(ranking); } } } } catch (Exception e) { e.printStackTrace(); throw new IllegalArgumentException("Invalid request for domain : " + domain); } return result; } } The domain phenomena.com ranked 3713994. Ranking: 3713994 ref. https://mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/
java · Jan. 16, 2023, 8:24 p.m.
XML
A simple way to read an XML file in Java
1. XML File <book> <person> <first>Kiran</first> <last>Pai</last> <age>22</age> </person> <person> <first>Bill</first> <last>Gates</last> <age>46</age> </person> <person> <first>Steve</first> <last>Jobs</last> <age>40</age> </person> </book> 2. Program Listing import java.io.File; import org.w3c.dom.Document; import org.w3c.dom.*; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class ReadAndPrintXMLFile{ public static void main (String argv []){ try { DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); Document doc = docBuilder.parse (new File("book.xml")); // normalize text representation doc.getDocumentElement ().normalize (); System.out.println ("Root element of the doc is " + doc.getDocumentElement().getNodeName()); NodeList listOfPersons = doc.getElementsByTagName("person"); int totalPersons = listOfPersons.getLength(); System.out.println("Total no of people : " + totalPersons); for(int s=0; s<listOfPersons.getLength() ; s++){ Node firstPersonNode = listOfPersons.item(s); if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){ Element firstPersonElement = (Element)firstPersonNode; //------- NodeList firstNameList = firstPersonElement.getElementsByTagName("first"); Element firstNameElement = (Element)firstNameList.item(0); NodeList textFNList = firstNameElement.getChildNodes(); System.out.println("First Name : " + ((Node)textFNList.item(0)).getNodeValue().trim()); //------- NodeList lastNameList = firstPersonElement.getElementsByTagName("last"); Element lastNameElement = (Element)lastNameList.item(0); NodeList textLNList = lastNameElement.getChildNodes(); System.out.println("Last Name : " + ((Node)textLNList.item(0)).getNodeValue().trim()); //---- NodeList ageList = firstPersonElement.getElementsByTagName("age"); Element ageElement = (Element)ageList.item(0); NodeList textAgeList = ageElement.getChildNodes(); System.out.println("Age : " + ((Node)textAgeList.item(0)).getNodeValue().trim()); //------ }//end of if clause }//end of for loop with s var }catch (SAXParseException err) { System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ()); System.out.println(" " + err.getMessage ()); }catch (SAXException e) { Exception x = e.getException (); ((x == null) ? e : x).printStackTrace (); }catch (Throwable t) { t.printStackTrace (); } //System.exit (0); }//end of main } 3. Program Output Root element of the doc is book Total no of people : 3 First Name : Kiran Last Name : Pai Age : 22 First Name : Bill Last Name : Gates Age : 46 First Name : Steve Last Name : Jobs Age : 40 https://www.developerfusion.com/code/2064/a-simple-way-to-read-an-xml-file-in-java/
java · Jan. 16, 2023, 8:15 p.m.
XML
Get MD5 Base64 : MD5 Message Digest algorithm
package com.bad.blood.test; /* * $Header: /cvsroot/mvnforum/mvnforum/contrib/phpbb2mvnforum/src/org/mvnforum/util/MD5.java,v 1.6 2007/01/15 10:27:31 dungbtm Exp $ * $Author: dungbtm $ * $Revision: 1.6 $ * $Date: 2007/01/15 10:27:31 $ * * * Copyright (C) 2002-2007 by MyVietnam.net * * All copyright notices regarding mvnForum MUST remain * intact in the scripts and in the outputted HTML. * The "powered by" text/logo with a link back to * http://www.mvnForum.com and http://www.MyVietnam.net in * the footer of the pages MUST remain visible when the pages * are viewed on the internet or intranet. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Support can be obtained from support forums at: * http://www.mvnForum.com/mvnforum/index * * Correspondence and Marketing Questions can be sent to: * info at MyVietnam net * * @author: */ import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; // The JavaReference.com Software License, Version 1.0 // Copyright (c) 2002-2005 JavaReference.com. All rights reserved. // // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. The end-user documentation included with the redistribution, if any, must // include the following acknowlegement: // // "This product includes software developed by the Javareference.com // (http://www.javareference.com/)." // // Alternately, this acknowlegement may appear in the software itself, if and // wherever such third-party acknowlegements normally appear. // // 4. The names "JavaReference" and "Javareference.com", must not be used to // endorse or promote products derived from this software without prior written // permission. For written permission, please contact webmaster@javareference.com. // // 5. Products derived from this software may not be called "Javareference" nor may // "Javareference" appear in their names without prior written permission of // Javareference.com. // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // JAVAREFERENCE.COM OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Software from this site consists of contributions made by various individuals // on behalf of Javareference.com. For more information on Javareference.com, // please see http://www.javareference.com /** * @author anandh */ public class MD5 { static char[] carr = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; public static String getBase64FromHEX(String input) { byte barr[] = new byte[16]; int bcnt = 0; for (int i = 0; i < 32; i += 2) { char c1 = input.charAt(i); char c2 = input.charAt(i + 1); int i1 = intFromChar(c1); int i2 = intFromChar(c2); barr[bcnt] = 0; barr[bcnt] |= (byte) ((i1 & 0x0F) << 4); barr[bcnt] |= (byte) (i2 & 0x0F); bcnt++; } return new String(Base64.getEncoder().encode(barr)); } public static synchronized String getMD5_Base64(String input) { // please note that we dont use digest, because if we // cannot get digest, then the second time we have to call it // again, which will fail again MessageDigest digest = null; try { digest = MessageDigest.getInstance("MD5"); } catch (Exception ex) { ex.printStackTrace(); } if (digest == null) return input; // now everything is ok, go ahead try { digest.update(input.getBytes("UTF-8")); } catch (java.io.UnsupportedEncodingException ex) { ex.printStackTrace(); } byte[] rawData = digest.digest(); return new String(Base64.getEncoder().encode(rawData)); } private static int intFromChar(char c) { char clower = Character.toLowerCase(c); for (int i = 0; i < carr.length; i++) { if (clower == carr[i]) { return i; } } return 0; } public static void main(String[] args) { //String password = args[0]; String password = "phenomena"; MessageDigest digest = null; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } try { digest.update(password.getBytes("UTF-8")); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } byte[] rawData = digest.digest(); StringBuffer printable = new StringBuffer(); for (int i = 0; i < rawData.length; i++) { printable.append(carr[((rawData[i] & 0xF0) >> 4)]); printable.append(carr[(rawData[i] & 0x0F)]); } String phpbbPassword = printable.toString(); System.out.println("PHPBB : " + phpbbPassword); System.out.println("MVNFORUM : " + getMD5_Base64(password)); System.out.println("PHPBB->MVNFORUM : " + getBase64FromHEX(phpbbPassword)); } } result: PHPBB : 93625b136e47b789af88d9c766b40064 MVNFORUM : k2JbE25Ht4mviNnHZrQAZA== PHPBB->MVNFORUM : k2JbE25Ht4mviNnHZrQAZA== ref. http://www.java2s.com/Tutorial/Java/0490__Security/GetMD5Base64.htm
java · Jan. 16, 2023, 8:19 a.m.
MD5
Encoding / Decoding as Base64 in Java
package com.bad.blood.test; import java.security.InvalidKeyException; import java.security.Key; import java.util.Base64; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.KeyGenerator; public class LocalEncrypter { private static String algorithm = "DESede"; private static Key key = null; private static Cipher cipher = null; private static void setUp() throws Exception { key = KeyGenerator.getInstance( algorithm ).generateKey(); cipher = Cipher.getInstance( algorithm ); } public static void main(String [] args) throws Exception { setUp(); byte [] encryptionBytes = null; String input = "phenomena"; System.out.println( "Entered: " + input ); encryptionBytes = encrypt( input ); String encodeString = new String(Base64.getEncoder().encode(encryptionBytes)); System.out.println( "Base64 Encode: " + encodeString ); System.out.println( "Recovered: " + decrypt( Base64.getDecoder().decode(encodeString) ) ); } private static byte [] encrypt(String input) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException { cipher.init( Cipher.ENCRYPT_MODE, key ); byte [] inputBytes = input.getBytes(); return cipher.doFinal(inputBytes); } private static String decrypt(byte [] encryptionBytes) throws InvalidKeyException, BadPaddingException, IllegalBlockSizeException { cipher.init( Cipher.DECRYPT_MODE, key ); byte [] recoveredBytes = cipher.doFinal( encryptionBytes ); String recovered = new String( recoveredBytes ); return recovered; } } result: Entered: phenomena Base64 Encode: lfE0CaaNbx1sGUJk6dwgjQ== Recovered: phenomena ref. https://stackoverflow.com/questions/13109588/encoding-as-base64-in-java   * Image to Base64 String Conversion package com.bad.blood.test; import java.io.File; import java.io.IOException; import java.util.Base64; import org.apache.commons.io.FileUtils; import org.junit.jupiter.api.Test; import static org.junit.Assert.assertTrue; public class FileToBase64StringConversionUnitTest { private String inputFilePath = "test_image.jpg"; private String outputFilePath = "test_image_copy.jpg"; @Test public void fileToBase64StringConversion() throws IOException { // load file from /src/test/resources ClassLoader classLoader = getClass().getClassLoader(); File inputFile = new File(classLoader .getResource(inputFilePath) .getFile()); byte[] fileContent = FileUtils.readFileToByteArray(inputFile); String encodedString = Base64 .getEncoder() .encodeToString(fileContent); // create output file File outputFile = new File(inputFile .getParentFile() .getAbsolutePath() + File.pathSeparator + outputFilePath); // decode the string and write to file byte[] decodedBytes = Base64 .getDecoder() .decode(encodedString); FileUtils.writeByteArrayToFile(outputFile, decodedBytes); assertTrue(FileUtils.contentEquals(inputFile, outputFile)); } } ref. https://www.baeldung.com/java-base64-image-string
java · Jan. 16, 2023, 8:06 a.m.
base64 encode decode
Play with JSoup
Removing Html tags except few specific ones from String in java public String clean(String unsafe){ Whitelist whitelist = Whitelist.none(); whitelist.addTags(new String[]{"p","br","ul"}); String safe = Jsoup.clean(unsafe, whitelist); return StringEscapeUtils.unescapeXml(safe); } For input string String unsafe = "<p class='p1'>paragraph</p>< this is not html > <a link='#'>Link</a> <![CDATA[<sender>John Smith</sender>]]>"; I get following output which is pretty much I require. <p>paragraph</p>< this is not html > Link <sender>John Smith</sender>
java · Jan. 14, 2023, 2:24 a.m.
jsoup
Django migrate gets error "table already exists"
1. Remove all migration files in <appname>/migrations 2. Remove all data in django_migrations table where app = <appname> 3.  python manage.py makemigrations <appname> 4.  python manage.py migrate --fake <appname> 5. If you have a field to alter, then alter the field <field> on <appname> and then again python manage.py makemigrations <appname> 6. python manage.py migrate <appname> Child's play.   0003이 실제로 적용된 가장 최근의 마이그레이션이라 가정할 때에는? --fake를 이용하여 현재 상태는 0003이다 라고 장고가 인식하게끔 해주어야 한다. python manage.py migrate --fake <appname> 0003 그 후 평소 하던대로 진행.   django 1.7 migrate gets error "table already exists" I am trying to apply a migration but am getting the error: django.db.utils.OperationalError: (1050, "Table 'customers_customer' already exists") I get this by issuing the following command: ... https://stackoverflow.com/questions/25924858/django-1-7-migrate-gets-error-table-already-exists How to redo a migration on django 1.8 after using --fake Something went wrong on my migrations, I added a new datetimefield to a model then I used makemigrations and migrate. python manage.py makemigrations python manage.py migrate But after this the m... https://stackoverflow.com/questions/30626886/how-to-redo-a-migration-on-django-1-8-after-using-fake
python · Jan. 12, 2023, 9:59 p.m.
django migration
How to change where a symlink points
files is a symbolic link to /media/files/tb-prod/files. When you access files or anything inside it, you'll really access the path under /media. Symbolic links are made and updated using the ln command. This link could have been made with: ln -s /media/files/tb-prod/files files -s means to make a symbolic link. To update a link, either delete the link and create it as above, or use the -f option to ln as well. If you are linking to a folder, you should include the -n option: ln -sfn /a/new/path files This will replace the link with a new one pointing at /a/new/path. The -n option is necessary when linking to a different target folder to avoid creating a sub-folder inside that symbolic link and instead replace the symbolic link completely. e.g. contact@me:/mnt/webdav$ ls a1  a2  a3  a4  a5  a6 contact@me:/mnt/webdav$ ln -sfn /mnt/a2/XYZ a2 contact@me:/mnt/webdav$ ls a1  a2  a3  a4  a5  a6 contact@me:/mnt/webdav$ https://unix.stackexchange.com/questions/151999/how-to-change-where-a-symlink-points
server · Jan. 12, 2023, 9:08 a.m.
Ubuntu linux
ubuntu 하드디스크 마운트
현재 시스템에 연결된 디스크 목록을 확인 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
server · Jan. 12, 2023, 8:19 a.m.
Ubuntu mount
우분투 서버에 삼바(SAMBA) 설치 및 설정
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
server · Jan. 12, 2023, 7:27 a.m.
Ubuntu samba
Fix SSL error when install packages using pip
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 
python · Jan. 12, 2023, 3:28 a.m.
ssl pip
Java Regular Expression
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("_+", "_")  
java · Jan. 12, 2023, 2:56 a.m.
regex
How do I create a screen capture using Robot class?
In this example you’ll see how to create a screen capture / screenshot and save it as an image file such a PNG image. Some classes are use in this program including the java.awt.Robot, java.awt.image.BufferedImage and javax.imageio.ImageIO. package org.kodejava.awt; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.awt.AWTException; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Robot; import java.io.File; import java.io.IOException; public class ScreenCapture { public static void main(String[] args) { try { Robot robot = new Robot(); // Capture screen from the top left in 200 by 200 pixel size. BufferedImage bufferedImage = robot.createScreenCapture( new Rectangle(new Dimension(200, 200))); // The captured image will the written into a file called // screenshot.png File imageFile = new File("screenshot.png"); ImageIO.write(bufferedImage, "png", imageFile); } catch (AWTException | IOException e) { e.printStackTrace(); } } } https://kodejava.org/how-do-i-create-a-screen-capture-using-robot-class/
java · Jan. 12, 2023, 2:44 a.m.
BufferedImage ImageIO Robot
  • 1
  • 2
  • 3
  • 4 (current)
  • 5