working on it ...

Filters

Explore Public Snippets

Sort by

Found 39k snippets

    public by ronrihoo modified Friday at 3:37:37 AM  122  0  5  0

    Example usage for the BackgroundColor class

    Companion usage example for the arbitrary libGDX Table BackgroundColor class.
    BackgroundColor backgroundColor = new BackgroundColor("white_color_texture.png");
    backgroundColor.setColor(2, 179, 228, 255); // r, g, b, a
    table.setBackground(backgroundColor);																														

    public by ronrihoo modified Friday at 3:13:48 AM  88  0  4  0

    Example helper class for GDXFacebook

    This helper class simplifies the usage of GDXFacebook in libGDX games and apps. (This is a backup to https://github.com/ronrihoo/GDX-Facebook-API-Helper and it's used in https://stackoverflow.com/a/46230835/6664817)
    // add package here
    
    import com.badlogic.gdx.Application;
    import com.badlogic.gdx.Gdx;
    import com.badlogic.gdx.utils.Array;
    import de.tomgrill.gdxfacebook.core.*;
    
    public class FacebookApi {
    
        private final static String CLASS_NAME = FacebookApi.class.getSimpleName();
        private final static String ERR_IN = "Error: in " + CLASS_NAME;
        private final static String EXC_IN = "Exception: in " + CLASS_NAME;
    
        private final static boolean VERBOSE_DEFAULT = true;
        private final static boolean DEBUG_DEFAULT = true;
    
        private boolean verbose;
        private boolean debug;
    
        private Array<String> permissions;
    
        private GDXFacebookConfig config;
        private GDXFacebook facebook;
        private GDXFacebookAccessToken token;
    
        /* if there's a class where credentials are stored or retrieved from,
         * then a constructor like this one could be used
         */ /*
        public FacebookApi() {
            this(Credentials.FB_API_ID);
        }
        /**/
    
        public FacebookApi(String appId) {
            this(appId, null, null);
        }
    
        /**
         *
         * @param appId The Facebook API ID is required.
         * @param prefFilename Optional (example: ".facebookSessionData").
         * @param apiVersion Optional. Graph API Version (default: v2.6).
         */
        public FacebookApi(String appId, String prefFilename, String apiVersion) {
            init(appId, prefFilename, apiVersion, DEBUG_DEFAULT);
        }
    
        private void init(String appId, String prefFilename,
                          String apiVersion, boolean debug) {
            setVerbose(VERBOSE_DEFAULT);
            setDebug(debug);
            if (appId != null) {
                setAppId(appId);
            } else {
                try {
                    throw new RuntimeException(EXC_IN +
                            ".init(...): appId is null. Has it been passed correctly?");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (prefFilename != null)
                setPrefFilename(prefFilename);
            if (apiVersion != null)
                setGraphApiVersion(apiVersion);
            initPermissionsArray();
            installGdxFacebookInstance();
            setGdxFacebookInstance();
            addBasicPermissions();
        }
    
        private void setGdxDebug(boolean debug) {
            debugLog("setGdxDebug(boolean debug)");
            if (debug)
                Gdx.app.setLogLevel(Application.LOG_DEBUG);
            // TODO: turn it off when debug == false
        }
    
        private void instantiateConfig() {
            debugLog("instantiateConfig()");
            config = new GDXFacebookConfig();
        }
    
        private boolean verifyConfig() {
            debugLog("verifyConfig()");
            if (config == null) {
                try {
                    instantiateConfig();
                }
                catch (Exception e) {
                    System.out.println(EXC_IN + ".verifyConfig(): \n" + e);
                    return false;
                }
            }
            return true;
        }
    
        private void setAppId(String appId) {
            debugLog("setAppId(String appId)");
            if (verifyConfig())
                config.APP_ID = appId;
        }
    
        private void setPrefFilename(String filename) {
            debugLog("setPrefFilename(String filename)");
            if (verifyConfig())
                config.PREF_FILENAME = filename;
        }
    
        private void setGraphApiVersion(String version) {
            debugLog("setGraphApiVersion(String version)");
            if (verifyConfig())
                config.GRAPH_API_VERSION = version;
        }
    
        private void installGdxFacebookInstance() {
            debugLog("installGdxFacebookInstance()");
            if (verifyConfig())
                facebook = GDXFacebookSystem.install(config);
        }
    
        /**
         * No parameters, as it is handled by GDXFacebookSystem
         */
        public void setGdxFacebookInstance() {
            debugLog("setGdxFacebookInstance()");
            if (facebook != null)
                facebook = GDXFacebookSystem.getFacebook();
        }
    
        /**
         *
         * @return GDXFacebook object.
         */
        public GDXFacebook getGdxFacebookInstance() {
            debugLog("getGdxFacebookInstance()");
            return facebook;
        }
    
        private void initPermissionsArray() {
            debugLog("initPermissionsArray()");
            permissions = new Array<String>();
        }
    
        private void addBasicPermissions() {
            debugLog("addBasicPermissions()");
            permissions.add("email");
            permissions.add("public_profile");
            permissions.add("user_friends");
        }
    
        public void addPermission(String permission) {
            debugLog("addPermission(String)");
            if (permissions != null)
                permissions.add(permission);
            else
                System.out.println(ERR_IN + ": permissions array is null");
        }
    
        /**
         * Basic sign-in with read-mode
         */
        public void signIn() {
            debugLog("signIn()");
            signIn(SignInMode.READ);
        }
    
        public void signIn(SignInMode signInMode) {
            debugLog("signIn(SignInMode)");
            if (facebook != null) {
                if (permissions == null) {
                    addBasicPermissions();
                    debug(CLASS_NAME +
                            ": returned to signIn(SignInMode) from addBasicPermissions()");
                }
                facebook.signIn(signInMode, permissions, new GDXFacebookCallback<SignInResult>() {
    
                    @Override
                    public void onSuccess(SignInResult result) {
                        if (verbose)
                            System.out.println("Successfully signed in Facebook.");
                        token = result.getAccessToken();
                        debug(CLASS_NAME + ".signIn() succeeded.");
                        debug(CLASS_NAME + ": accessToken is " + token);
                    }
    
                    @Override
                    public void onError(GDXFacebookError error) {
                        if (debug)
                            System.out.println(ERR_IN + ".signIn(): " +
                                    error.getErrorMessage());
                        debug("signIn() invoked by GDXFacebook instance, facebook, in " +
                                CLASS_NAME + " faced an error.");
                    }
    
                    @Override
                    public void onCancel() {
                        // When the user cancels the login process
                        debug("signIn() invoked by GDXFacebook instance, facebook, in " +
                                CLASS_NAME + " canceled.");
                    }
    
                    @Override
                    public void onFail(Throwable t) {
                        // When the login fails
                        debug("signIn() invoked by GDXFacebook instance, facebook, in " +
                                CLASS_NAME + " failed.");
                    }
                });
            } else {
                debug(ERR_IN + ".signIn(): " +
                        "GDXFacebook instance, facebook, is null.");
            }
        }
    
        public void signOut() {
            debug(CLASS_NAME + ".signOut()");
            facebook.signOut();
        }
    
        protected void setVerbose(boolean verbose) {
            this.verbose = verbose;
        }
    
        protected void setDebug(boolean debug) {
            this.debug = debug;
            setGdxDebug(debug);
        }
    
        private void debug(String msg) {
            if (debug)
                System.out.println(msg);
        }
    
        private void debugLog(String methodName) {
            if (verbose)
                debug(CLASS_NAME + "." + methodName);
        }
    
    }

    public by ronrihoo modified Sep 9, 2017  203  3  5  1

    libGDX Table background color

    Create an instance of this class by giving the constructor the filename of a white PNG from your project resources. Then, use one of the instance's setColor(red, green, blue, alpha) methods. Finally, pass the instance to the libGDX Table using the Table's setBackground(Drawable drawable) method. This is not meant to be a perfect solution for all --
    import com.badlogic.gdx.Gdx;
    import com.badlogic.gdx.graphics.Color;
    import com.badlogic.gdx.graphics.Texture;
    import com.badlogic.gdx.graphics.g2d.Batch;
    import com.badlogic.gdx.graphics.g2d.Sprite;
    import com.badlogic.gdx.graphics.g2d.TextureRegion;
    import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
    
    public class BackgroundColor implements Drawable {
    	
    	private Float x;
    	private Float y;
    	private Float width;
    	private Float height;
    	
    	private Boolean fillParent;
    	
    	private String filename;
    	private Texture texture;
    	private TextureRegion textureRegion;
    	private Sprite sprite;
    	private Color color;
    	
    	public BackgroundColor(String filename) {
    		this(filename, 0.0f, 0.0f, 0.0f, 0.0f);
    	}
    	
    	public BackgroundColor(String filename, float x, float y) {
    		this(filename, x, y, 0.0f, 0.0f);
    	}
    	
    	public BackgroundColor(String filename, float x, float y, float width, float height) {
    		this.setPosition(x, y);
    		this.setSize(width, height);
    		initialize(filename);
    	}
    	
    	private void initialize(String filename) {
    		setFilename(filename);
    		if (x == null || y == null)
    			setPosition();	// x = 0.0f; y = 0.0f;
    		if (width == null || height == null || width < 0.0f || height < 0.0f)
    			setSize();		// width = 0.0f; height = 0.0f;
    		if (color == null)
    			setColor(255, 255, 255, 255);
    		if (sprite == null) {
    			try {
    				setSprite();
    			} catch (Exception e) {
    				System.err.println(e);
    			}
    		}
    		if (fillParent == null)
    			fillParent = true;
    	}
    	
    	private void setTexture() {
    		if (texture != null)
    			texture.dispose();
    		texture = new Texture(Gdx.files.internal(getFilename()));
    	}
    	
    	private void setTextureRegion() {
    		textureRegion = new TextureRegion(texture, (int) getWidth(), (int) getHeight());
    	}
    	
    	private void setSprite() {
    		if (texture == null)
    			setTexture();
    		setTextureRegion();
    		sprite = new Sprite(textureRegion);
    		setSpriteColor();
    	}
    	
    	private void setSpriteColor() {
    		sprite.setColor(color.r, color.g, color.b, color.a);
    	}
    	
    	private void setPosition() {
    		this.x = 0.0f;
    		this.y = 0.0f;
    	}
    	
    	private void setPosition(float x, float y) {
    		this.x = x;
    		this.y = y;
    	}
    	
    	private void setSize() {
    		this.width = sprite.getWidth();
    		this.height = sprite.getHeight();
    	}
    	
    	private void setSize(float width, float height) {
    		this.width = width;
    		this.height = height;
    	}
    	
    	public void setColor(int r, int g, int b, int a) {
    		color = new Color(r/255f, g/255f, b/255f, a/255f);
    	}
    
    	public void setColor(float r, float g, float b, float a) {
    		color = new Color(r/255f, g/255f, b/255f, a/255f);
    	}
    	
    	private void setSpritePosition(float x, float y) {
    		sprite.setX(x);
    		sprite.setY(y);
    	}
    	
    	private void updateSprite(float x, float y, float width, float height) {
    		if (fillParent) {
    			setSpritePosition(x, y);
    			if (width != textureRegion.getRegionWidth() || 
    					height != textureRegion.getRegionHeight()) {
    				setSize(width, height);
    				setSprite();
    			}
    		}
    	}
    	
    	@Override
    	public void draw(Batch batch, float x, float y, float width, float height) {
    		updateSprite(x, y, width, height);
    		sprite.draw(batch);
    	}
    
    	@Override
    	public float getLeftWidth() {
    		// TODO Auto-generated method stub
    		return 0;
    	}
    
    	@Override
    	public void setLeftWidth(float leftWidth) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	@Override
    	public float getRightWidth() {
    		// TODO Auto-generated method stub
    		return 0;
    	}
    
    	@Override
    	public void setRightWidth(float rightWidth) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	@Override
    	public float getTopHeight() {
    		// TODO Auto-generated method stub
    		return 0;
    	}
    
    	@Override
    	public void setTopHeight(float topHeight) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	@Override
    	public float getBottomHeight() {
    		// TODO Auto-generated method stub
    		return 0;
    	}
    
    	@Override
    	public void setBottomHeight(float bottomHeight) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	@Override
    	public float getMinWidth() {
    		// TODO Auto-generated method stub
    		return 0;
    	}
    
    	@Override
    	public void setMinWidth(float minWidth) {
    		// TODO Auto-generated method stub
    		
    	}
    
    	@Override
    	public float getMinHeight() {
    		// TODO Auto-generated method stub
    		return 0;
    	}
    
    	@Override
    	public void setMinHeight(float minHeight) {
    		// TODO Auto-generated method stub
    		
    	}
    	
    	private void setFilename(String filename) {
    		this.filename = filename;
    	}
    	
    	private String getFilename() {
    		return filename;
    	}
    
    	public float getX() {
    		return x;
    	}
    
    	public void setX(float x) {
    		this.x = x;
    	}
    
    	public float getY() {
    		return y;
    	}
    
    	public void setY(float y) {
    		this.y = y;
    	}
    
    	public float getWidth() {
    		return width;
    	}
    
    	public void setWidth(float width) {
    		this.width = width;
    	}
    
    	public float getHeight() {
    		return height;
    	}
    
    	public void setHeight(float height) {
    		this.height = height;
    	}
    
    	public Boolean getFillParent() {
    		return fillParent;
    	}
    
    	public void setFillParent(Boolean fillParent) {
    		this.fillParent = fillParent;
    	}
    
    }
    																																				

    public by snip2code modified Aug 13, 2017  45  0  2  0

    First Snippet: How to play with Snip2Code

    This is the first example of a snippet: - the title represents in few words which is the exact issue the snippet resolves; it can be something like the name of a method; - the description (this field) is an optional field where you can add interesting information regarding the snippet; something like the comment on the head of a method; - the c
    /* place here the actual content of your snippet. 
       It should be code or pseudo-code. 
       The less dependencies from external stuff, the better! */

    public by cghersi modified Jan 10, 2017  2026  9  5  3

    How to write bytes into file in Java

    Efficient way to write strings or bytes onto a file.
      import java.nio.file.Files;
      import java.nio.file.Paths;
    
      public static void writeFile(String path, String content) throws Exception {
    		if (isNullOrEmpty(path) || isNullOrEmpty(content)) {
    			return;
    		}
    		Files.write(Paths.get(path), content.getBytes());
    	}                     

    public by cghersi modified Jan 10, 2017  2229  2  5  1

    Read file in Java

    Efficient way to read file in Java using Files class
      import java.nio.file.Files; 
      import java.nio.file.Paths;
    
      public static String readFile(String path) throws Exception {
    		if (isNullOrEmpty(path)) {
    			return "";
    		}
    		return new String(Files.readAllBytes(Paths.get(path)));
    	}      

    public by cghersi modified Dec 16, 2016  1964  5  6  0

    How to post an HTTP Request

    just consume a RESTful API via POST request
    public String sendPostReq(String url, String data, boolean addAccessToken) {
    		// Create a new client:
    		DefaultHttpClient httpClient = createHttpClient(url.startsWith("https"));
    		HttpPost httppost = new HttpPost(url);
    		httppost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    		httppost.setHeader("Charset", "UTF-8");
    		httppost.setHeader("Accept", m_requestFormat.getMimeType());
    		httppost.setHeader(S2C_HEADER, S2C_HEADER_VALUE);
    
    		//access the secured service with the authorization cookie
    		if (addAccessToken && !Utils.isNullOrEmpty(m_accessToken)) {
    			addAccessTokenToCookies();
    		}
    		httpClient.setCookieStore(m_cookies);
    		try {
    			httppost.setEntity(new StringEntity(data, "UTF-8"));
    		} catch (UnsupportedEncodingException e1) {
    			log.error("Cannot encode data: " + data + " due to " + e1);
    			return "";
    		}
    
    		HttpResponse response = null;
    		String res = "";
    		try {
    			response = httpClient.execute(httppost);
    			res = readStreamData(response.getEntity().getContent());
    			log.info("Response:" + res);
    		} catch (org.apache.http.conn.HttpHostConnectException e) {
    			log.error("Cannot receive response due to " + e);
    			if (url.contains(LOGIN_URL))
    				res = TIMEOUT_RESP;
    		} catch (IOException e) {
    			log.error("Cannot parse incoming response due to " + e);
    		} finally {
    			httpClient.getConnectionManager().shutdown();
    		}
    		
    		m_cookies = httpClient.getCookieStore(); //save cookies for the next secured run		
    		return res;
    	}

    public by hburaksavas modified Nov 23, 2016  8348  1  4  0

    Creating String Objects With Java

    Creating String Objects With Java: Java:CreatingString.java
    public class CreatingString{
      
      public static void main(String[] args){
        
        String ad;
        ad= "Burak";
        
        String soyad = "Savaş";
        
        String adres = new String("İstanbul - Ataşehir");
        
        System.out.println("Yazar bilgileri");
        System.out.println(ad);
        System.out.println(soyad);
        System.out.println(adres);
        
      }
    }
    
    

    public by DinhoPutz modified Aug 23, 2016  10916  1  5  0

    Calculadora Básica em Java (4 operações)

    // Enter here the actual content of the snippet.            package calculadora;
    public class Calculadora {
    	
        public static void main(String[] args) {
    		
    		double valor1 = 0;
            double valor2 = 0;
    		char operador = ' ';
    		double resultado = 0;
    		
    		System.out.println("Hello World");
    		
    		
    		System.out.println("Digite o primeiro digito");
    		
    		valor1 = new java.util.Scanner(System.in).nextDouble();
    		
    		System.out.println("Valor 1: " + valor1);
    		
    		while(true){
    			System.out.println("Digite o operador (+, -, /, *) ");
    			operador = new java.util.Scanner(System.in).next().charAt(0);
    			if (operador == '+' || operador == '-' || operador == '/' || operador == '*'){
    				break; // Sai da extrutura de repetição
    			}
    			else{
    				System.out.println("Operador inválido. Tente novamente");
    			}
    		}
    		
    		System.out.println("Digite o segundo digito");
    		
    		valor2 = new java.util.Scanner(System.in).nextDouble();
    		
    		switch(operador){
    			case '+':
    			resultado = valor1 + valor2;
    			break;
    			
    			case '-':
    			resultado = valor1 - valor2;
    			break;
    			
    			case '*':
    			resultado = valor1 * valor2;
    			break;
    			
    			case '/':
    			resultado = valor1 / valor2;
    			break;
    		}
    		
    		System.out.println("Resultado: " + resultado);
    		
    		
    	}
    } 
    
    

    public by sherazam modified Jun 8, 2016  182060  1  5  0

    How to Delete Messages in Bulk or One by One from Outlook PST in .NET Apps

    This technical tip explains how .NET developers can Delete Messages from outlook PST. Add Messages to PST Files showed how to add messages to PST files. It is, of course, also possible to delete items (contents) from a PST file and it may also be desirable to delete messages in bulk. Items from a PST file can be deleted using the FolderInfo.DeleteC
    // Enter here the actual content of the snippet.            
    //Deleting Messages from PST Files
    
    //The code snippets below delete messages from a PST file's Sent subfolder.
    
    //[C# Code Sample]
    
    // Get the Sent items folder
    FolderInfo folderInfo = pst.GetPredefinedFolder(StandardIpmFolder.SentItems);
    MessageInfoCollection msgInfoColl = folderInfo.GetContents();
    foreach (MessageInfo msgInfo in msgInfoColl)
    {
        Console.WriteLine(msgInfo.Subject + ": " + msgInfo.EntryIdString);
        if (msgInfo.Subject.Equals("some delete condition") == true)
        {
            // Delete this item
            folderInfo.DeleteChildItem(msgInfo.EntryId);
            Console.WriteLine("Deleted this message");
        }
    }
     
    //[VB.NET Code Sample]
    
    ' Get the Sent items folder
    Dim folderInfo As FolderInfo = pst.GetPredefinedFolder(StandardIpmFolder.SentItems)
    Dim msgInfoColl As MessageInfoCollection = folderInfo.GetContents()
    For Each msgInfo As MessageInfo In msgInfoColl
    	Console.WriteLine(msgInfo.Subject & ": " & msgInfo.EntryIdString)
    	If msgInfo.Subject.Equals("some delete condition") = True Then
    		' Delete this item
    		folderInfo.DeleteChildItem(msgInfo.EntryId)
    		Console.WriteLine("Deleted this message")
    	End If
    Next msgInfo
    
    //Delete Items in Bulk from PST File
    
    //Aspose.Email API can be used to delete items in bulk from a PST file. This is achieved using the DeleteChildItems method which accepts a list of Entry ID items referring to the items to be deleted.
    
    //[C# Code Sample]
    
    using (PersonalStorage pst = PersonalStorage.FromFile(@"test.pst"))
    {
        FolderInfo inbox = pst.RootFolder.GetSubFolder("Inbox");
        
        // find messages having From = "someuser@domain.com" 
        PersonalStorageQueryBuilder queryBuilder = new PersonalStorageQueryBuilder();
        queryBuilder.From.Contains("someuser@domain.com");
        MessageInfoCollection messages = inbox.GetContents(queryBuilder.GetQuery());
        IList<string> deleteList = new List<string>();
        foreach (MessageInfo messageInfo in messages)
        {
            deleteList.Add(messageInfo.EntryIdString);
        }
        
        // delete messages having From = "someuser@domain.com"
        inbox.DeleteChildItems(deleteList);
    }
    
    //[VB.NET Code Sample]
    
    Using pst As PersonalStorage = PersonalStorage.FromFile("test.pst")
    	Dim inbox As FolderInfo = pst.RootFolder.GetSubFolder("Inbox")
    
    	' find messages having From = "someuser@domain.com" 
    	Dim queryBuilder As New PersonalStorageQueryBuilder()
    	queryBuilder.From.Contains("someuser@domain.com")
    	Dim messages As MessageInfoCollection = inbox.GetContents(queryBuilder.GetQuery())
    	Dim deleteList As IList(Of String) = New List(Of String)()
    	For Each messageInfo As MessageInfo In messages
    		deleteList.Add(messageInfo.EntryIdString)
    	Next
    
    	' delete messages having From = "someuser@domain.com"
    	inbox.DeleteChildItems(deleteList)
    End Using
    
    
    • Public Snippets
    • Channels Snippets